<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="销售组织" prop="orgguid">
        <el-select v-model="queryParams.orgguid" placeholder="请选择销售组织" size="small" clearable>
            <el-option
              v-for="item in organizationOptions"
              :key="item.guid"
              :label="item.name"
              :value="item.guid"
            ></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="采购组织" prop="purorgguid">
        <el-select v-model="queryParams.purorgguid" placeholder="请选择采购组织" size="small" clearable>
            <el-option
              v-for="item in organizationOptions"
              :key="item.guid"
              :label="item.name"
              :value="item.guid"
            ></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="产品" prop="productguid">
        <el-select v-model="queryParams.productguid" placeholder="请选择产品" clearable filterable >
            <el-option
              v-for="item in productOptions"
              :key="item.guid"
              :label="item.productname"
              :value="item.guid"
              @click.native="getSp($event, item)"
            ></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="物料" prop="spguid">
        <el-input
          v-model="queryParams.spname"
          placeholder="请输入规格"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生效时间" prop="effectivetime">
        <el-date-picker clearable size="small" style="width: 192px;"
                        v-model="queryParams.effectivetime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择生效时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
          v-hasPermi="['product:innerprice:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="small"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:innerprice:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:innerprice:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="small"
          @click="handleExport"
          v-hasPermi="['product:innerprice:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="innerpriceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="销售组织" align="center" prop="xname" width="90" />
      <el-table-column label="采购组织" align="center" prop="cname" width="90" />
      <el-table-column label="产品" align="center" prop="productname" width="120" />
      <el-table-column label="规格" align="center" prop="spname" width="180" />
      <el-table-column label="价格" align="center" prop="price" >
        <template slot-scope="scope">
            <span>{{scope.row.price}}元 / {{scope.row.unit}}</span>
          </template>
        </el-table-column>
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="创建时间" align="center" prop="createtime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createtime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生效时间" align="center" prop="effectivetime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.effectivetime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="center" prop="nickName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:innerprice:edit']"
          >修改</el-button>
          <el-button
            size="small"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:innerprice:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改内部价格对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body @close="closeDialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="销售组织" prop="orgguid">
          <el-select v-model="form.orgguid" placeholder="请选择销售组织">
            <el-option
              v-for="item in organizationOptions"
              :key="item.guid"
              :label="item.name"
              :value="item.guid"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采购组织" prop="purorgguid">
          <el-select v-model="form.purorgguid" placeholder="请选择采购组织">
            <el-option
              v-for="item in organizationOptions"
              :key="item.guid"
              :label="item.name"
              :value="item.guid"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生效时间" prop="effectivetime">
          <el-date-picker clearable size="small" style="width: 200px"
            v-model="form.effectivetime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择生效时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="产品">
          <el-upload
            :limit="1"
            ref="uploader"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url"
            :disabled="upload.isUploading"
            :on-success="handleFileSuccess"
            name="file"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
            </div>
            <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
          </el-upload>
        </el-form-item>
        <!-- <el-form-item label="规格" prop="spguid">
          <el-input v-model="form.spguid" placeholder="请输入规格" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格" />
        </el-form-item> -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改内部价格对话框 -->
    <el-dialog title="修改内部价格" :visible.sync="openEdit" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="销售组织" prop="orgguid">
           <el-select v-model="form.orgguid" placeholder="请选择销售组织">
            <el-option
              v-for="item in organizationOptions"
              :key="item.guid"
              :label="item.name"
              :value="item.guid"
            ></el-option>
          </el-select>
        </el-form-item>
         <el-form-item label="采购组织" prop="purorgguid">
          <el-select v-model="form.purorgguid" placeholder="请选择采购组织">
            <el-option
              v-for="item in organizationOptions"
              :key="item.guid"
              :label="item.name"
              :value="item.guid"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品">
          <el-select v-model="form.productguid" placeholder="请选择产品">
            <el-option
              v-for="item in productOptions"
              :key="item.guid"
              :label="item.productname"
              :value="item.guid"
              @click.native="getSp($event, item)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格" prop="spguid">
          <el-select v-model="form.spguid" placeholder="请选择规格">
            <el-option
              v-for="item in spOptions"
              :key="item.guid"
              :label="item.name"
              :value="item.guid"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="生效时间" prop="effectivetime">
          <el-date-picker clearable size="small" style="width: 200px"
            v-model="form.effectivetime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择生效时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="openEdit=false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInnerprice, getInnerprice, delInnerprice, addInnerprice, updateInnerprice, exportInnerprice, importTemplate } from "@/api/product/innerprice";
import UploadImage from '@/components/UploadImage';
import { findOrganizationList, findProductList,findSpecificationList } from "@/api/public";
import { getToken } from "@/utils/auth";

export default {
  name: "Innerprice",
  components: {
    UploadImage,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 内部价格表格数据
      innerpriceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orgguid: null,
        purorgguid: null,
        productguid: null,
        spguid: null,
        effectivetime: null,
        status: null,
        lastupdatetime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orgguid: [
          { required: true, message: "销售组织id不能为空", trigger: "blur" }
        ],
        productguid: [
          { required: true, message: "产品不能为空", trigger: "blur" }
        ],
        spguid: [
          { required: true, message: "规格不能为空", trigger: "blur" }
        ],
        effectivetime: [
          { required: true, message: "生效时间不能为空", trigger: "blur" }
        ],
      },
      organizationOptions: [],
       // 导入参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      },
      openEdit: false,
      productOptions: [],
      spOptions: [],
      spParams: {productguid: null,},
    };
  },
  created() {
    this.getList();
    this.findOrganizationList();
    this.findProductList();
    this.getDicts("general_status").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    closeDialog: function() {
      this.$refs.uploader.clearFiles();
    },
    getSp(event, item){
      this.spParams.productguid = item.guid;
      this.findSpecificationList();
    },
    findProductList(){
      findProductList().then(response => {
        this.productOptions = response.data;
      });
    },
    findOrganizationList(){
      findOrganizationList().then(response => {
        this.organizationOptions = response.data;
      });
    },
    /** 查询内部价格列表 */
    getList() {
      this.loading = true;
      listInnerprice(this.queryParams).then(response => {
        this.innerpriceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    findSpecificationList(){
      findSpecificationList(this.spParams).then(response => {
        this.spOptions = response.data;
      });
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orgguid: null,
        purorgguid: null,
        productguid: null,
        spguid: null,
        price: null,
        status: null,
        createdby: null,
        createtime: null,
        effectivetime: null,
        lastupdatetime: null,
        templateUrl: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加内部价格";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getInnerprice(id).then(response => {
        this.spParams.productguid = response.data.productguid;
        this.findSpecificationList();
        this.form = response.data;
        this.openEdit = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInnerprice(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.openEdit = false;
              this.getList();
            });
          } else {
            addInnerprice(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除该数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delInnerprice(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有内部价格数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportInnerprice(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
     /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.form.templateUrl = process.env.VUE_APP_BASE_API + response.fileName;
      this.msgSuccess("上传成功");
    },
  }
};
</script>
